﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Web;
using System.IO;

namespace XTYAPI.通讯.WebAPI
{
    /// <summary>
    /// 待验证
    /// </summary>
    public class WebApiClient
    {
        HttpClient client = new HttpClient();
        public WebApiClient() { }
        public WebApiClient(string url = "https://api.example.com/")
        {
            /*
             我们使用了HttpClient类来发送HTTP请求。首先，我们设置了BaseAddress属性为Web API的基址，然后设置了DefaultRequestHeaders.Accept属性为application/json，表示我们希望接收JSON格式的响应。
             接下来
            
            下面我们使用GetAsync方法发送GET请求，并等待响应。如果响应的状态码表示请求成功，我们使用ReadAsStringAsync方法读取响应内容，并显示在消息框中。如果请求失败，我们显示一个包含状态码的错误消息。
             如果在请求过程中发生异常，我们捕获异常并显示异常消息。请注意，上面的示例代码中使用了async和await关键字来实现异步操作，这样可以避免阻塞UI线程，提高程序的响应性能。
             */
            client.BaseAddress = new Uri(url);
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));


        }
        public async Task<bool> Get()
        {
            // 构造查询参数
            string jsonParam = "{\"key\":\"value\"}";
            string encodedJsonParam = jsonParam/*HttpUtility.UrlEncode(jsonParam)*/;

            // 发送GET请求
            HttpResponseMessage response = await client.GetAsync($"api/values?json={encodedJsonParam}");
            if (response.IsSuccessStatusCode)
            {
                string result = await response.Content.ReadAsStringAsync();
                MessageBox.Show(result);
            }
            else
            {
                MessageBox.Show("请求失败，状态码：" + response.StatusCode);
            }
            return true;
        }
        /// <summary>
        /// 避免死锁的写法
        /// </summary>
        /// <returns></returns>
        public bool Get11()
        {
            return Task.Run(() =>
            {
                string jsonParam = "{\"key\":\"value\"}";
                string encodedJsonParam = jsonParam;

                // 使用ConfigureAwait(false)避免上下文捕获
                var response = client.GetAsync($"api/values?json={encodedJsonParam}")
                                   .ConfigureAwait(false)
                                   .GetAwaiter()
                                   .GetResult();

                if (response.IsSuccessStatusCode)
                {
                    string result = response.Content.ReadAsStringAsync()
                                                 .ConfigureAwait(false)
                                                 .GetAwaiter()
                                                 .GetResult();
                    MessageBox.Show(result);
                }
                else
                {
                    MessageBox.Show("请求失败，状态码：" + response.StatusCode);
                }

                return true;
            }).Result;
        }

        public bool Get12()
        {
            // 构造查询参数
            string jsonParam = "{\"key\":\"value\"}";
            string encodedJsonParam = jsonParam; // 如需URL编码可取消注释

            // 发送GET请求（同步方式）
            HttpResponseMessage response = client.GetAsync($"api/values?json={encodedJsonParam}").Result;

            if (response.IsSuccessStatusCode)
            {
                string result = response.Content.ReadAsStringAsync().Result;
                MessageBox.Show(result);
            }
            else
            {
                MessageBox.Show("请求失败，状态码：" + response.StatusCode);
            }

            return true;
        }
        public async Task<bool> Post11(string data, string url = "api/values")
        {
            // 构造POST请求的数据
            string postData = "{\"key\":\"value\"}";
            HttpContent content = new StringContent(postData, Encoding.UTF8, "application/json");

            // 发送POST请求
            HttpResponseMessage response = await client.PostAsync(url, content);
            if (response.IsSuccessStatusCode)
            {
                string result = await response.Content.ReadAsStringAsync();
                MessageBox.Show(result);
            }
            else
            {
                MessageBox.Show("请求失败，状态码：" + response.StatusCode);
            }
            return true;
        }

        public bool Post12(string data, string url = "api/values")
        {
            return Task.Run(async () =>
            {
                string postData = "{\"key\":\"value\"}";
                HttpContent content = new StringContent(postData, Encoding.UTF8, "application/json");

                HttpResponseMessage response = await client.PostAsync(url, content).ConfigureAwait(false);

                if (response.IsSuccessStatusCode)
                {
                    string result = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                    MessageBox.Show(result);
                }
                else
                {
                    MessageBox.Show("请求失败，状态码：" + response.StatusCode);
                }

                return true;
            }).Result;
        }
        public bool Post13(string data, string url = "api/values")
        {
            // 构造POST请求的数据
            string postData = "{\"key\":\"value\"}";
            HttpContent content = new StringContent(postData, Encoding.UTF8, "application/json");

            // 发送POST请求（同步方式）
            HttpResponseMessage response = client.PostAsync(url, content).Result;

            if (response.IsSuccessStatusCode)
            {
                string result = response.Content.ReadAsStringAsync().Result;
                MessageBox.Show(result);
            }
            else
            {
                MessageBox.Show("请求失败，状态码：" + response.StatusCode);
            }

            return true;
        }

        /// <summary>
        /// 用流的形式post
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task<bool> Post1(string data, string url = "api/values")
        {
            /// 构造请求内容
            string jsonContent = "{\"key\":\"value\"}";
            byte[] byteArray = Encoding.UTF8.GetBytes(jsonContent);
            using (MemoryStream stream = new MemoryStream(byteArray))
            {
                using (StreamContent content = new StreamContent(stream))
                {
                    content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");

                    // 发送POST请求
                    HttpResponseMessage response = await client.PostAsync(url, content);
                    if (response.IsSuccessStatusCode)
                    {
                        string result = await response.Content.ReadAsStringAsync();
                        MessageBox.Show(result);
                    }
                    else
                    {
                        MessageBox.Show("请求失败，状态码：" + response.StatusCode);
                    }
                }
            }
            return true;
        }

        public bool Post21(string data, string url = "api/values")
        {
            // 构造请求内容
            string jsonContent = "{\"key\":\"value\"}";
            byte[] byteArray = Encoding.UTF8.GetBytes(jsonContent);

            using (MemoryStream stream = new MemoryStream(byteArray))
            {
                using (StreamContent content = new StreamContent(stream))
                {
                    content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");

                    // 发送POST请求（同步方式）
                    HttpResponseMessage response = client.PostAsync(url, content).Result;

                    if (response.IsSuccessStatusCode)
                    {
                        string result = response.Content.ReadAsStringAsync().Result;
                        MessageBox.Show(result);
                    }
                    else
                    {
                        MessageBox.Show("请求失败，状态码：" + response.StatusCode);
                    }
                }
            }

            return true;
        }

        /// <summary>
        /// 建议用下面方法减少死锁
        /// </summary>
        /// <param name="data"></param>
        /// <param name="url"></param>
        /// <returns></returns>
        public bool Post22(string data, string url = "api/values")
        {
            return Task.Run(() =>
            {
                string jsonContent = "{\"key\":\"value\"}";
                byte[] byteArray = Encoding.UTF8.GetBytes(jsonContent);

                using (MemoryStream stream = new MemoryStream(byteArray))
                {
                    using (StreamContent content = new StreamContent(stream))
                    {
                        content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");

                        // 使用 ConfigureAwait(false) 避免上下文捕获
                        HttpResponseMessage response = client.PostAsync(url, content).ConfigureAwait(false).GetAwaiter().GetResult();

                        if (response.IsSuccessStatusCode)
                        {
                            string result = response.Content.ReadAsStringAsync().ConfigureAwait(false).GetAwaiter().GetResult();
                            MessageBox.Show(result);
                        }
                        else
                        {
                            MessageBox.Show("请求失败，状态码：" + response.StatusCode);
                        }
                    }
                }

                return true;
            }).Result;
        }
    }
}
